package top.zsyle.sycc.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zsyle.sycc.domain.Course;
import top.zsyle.sycc.domain.MessageSms;
import top.zsyle.sycc.domain.User;
import top.zsyle.sycc.mapper.MessageSmsMapper;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RocketMQMessageListener(
        consumerGroup = "course-consumer",
        topic = "course-topic",
        selectorExpression = "notice-tag",
        messageModel = MessageModel.CLUSTERING
)
@Component
@Slf4j
public class CourseSendMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private MessageSmsMapper messageSmsMapper;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if (body == null||body.length == 0){
            log.info("发送课程上架消息失败！");
            return;
        }
        String str = new String(body, StandardCharsets.UTF_8);
        Course course = JSONObject.parseObject(str, Course.class);
        // 2.准备发送的内容
        String message = "亲爱的用户您好，最新课程 <a href='localhost:6002/detail.html?courseId="+course.getId()+"'> "+course.getName()+" </a> 发布啦，点击课程了解详情";
        //查询所有有关系的用户（订阅，购买，查看，浏览过，收藏过，等等）
        List<User> users = Arrays.asList(new User(1L, "18911111111"), new User(2L, "18122222222"), new User(3L, "18933333333"));
        sendSms(message,users);
//        sendEmail(message);
//        sendStation(message);
    }

    private void sendSms(String message,List<User> users) {
        ArrayList<MessageSms> messageSmsList= new ArrayList<>();
        //发送短信
        users.forEach(e->{
            log.info(message+":"+e.getId());
            MessageSms messageSms = new MessageSms();
            messageSms.setSendTime(new Date());
            messageSms.setTitle("课程发布");
            messageSms.setContent(message);
            messageSms.setUserId(e.getId());
            messageSmsList.add(messageSms);
        });
        messageSmsMapper.addBatch(messageSmsList);
    }
}
